﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace IEC
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public static GameConfig config;
        GameOption option;
        ModList mods;
        public static IECConfig myConfig;

        public static int VERSION_MAJOR = 1, VERSION_MINOR = 1;
        public MainWindow()
        {
            myConfig = new IECConfig();
            config = new GameConfig();
            option = new GameOption();
            mods = new ModList();

            InitializeComponent();

            this.Title += " （版本号：" + VERSION_MAJOR + "." + VERSION_MINOR + "）";

            ReloadConfigs();
            UpdateConfigUI();
        }


        public void ReloadConfigs()
        {
            option.LoadOption();
            mods.UpdateList();
        }
        public void UpdateConfigUI()
        {
            GamePathLabel.Text = config.GetGamePath();
            GameOptionLabel.Text = config.GetOptionPath();
            ModPathLabel.Text = config.GetModPath();
            ModDataLabel.Text = config.GetModDataPath();

            if (option.Dict.ContainsKey("EnableDebugConsole"))
            {
                OptionConsoleEnabled.IsEnabled = true;
                OptionConsoleEnabled.IsChecked = option.Dict["EnableDebugConsole"] == "1";
            }
            else
            {
                OptionConsoleEnabled.IsEnabled = false;
                OptionConsoleEnabled.IsChecked = false;
            }


            if (option.Dict.ContainsKey("EnableMods"))
            {
                OptionModEnabled.IsEnabled = true;
                OptionModEnabled.IsChecked = option.Dict["EnableMods"] == "1";
            }
            else
            {
                OptionModEnabled.IsEnabled = false;
                OptionModEnabled.IsChecked = false;
            }
            if (option.Dict.ContainsKey("PauseOnFocusLost"))
            {
                PauseOnFocusLostEnabled.IsEnabled = true;
                PauseOnFocusLostEnabled.IsChecked = option.Dict["PauseOnFocusLost"] == "1";
            }
            else
            {
                PauseOnFocusLostEnabled.IsEnabled = false;
                PauseOnFocusLostEnabled.IsChecked = false;
            }
            if (option.Dict.ContainsKey("MouseControl"))
            {
                MouseControlEnabled.IsEnabled = true;
                MouseControlEnabled.IsChecked = option.Dict["MouseControl"] == "1";
            }
            else
            {
                MouseControlEnabled.IsEnabled = false;
                MouseControlEnabled.IsChecked = false;
            }

            ModListStackPanel.Children.Clear();

            var unSyncMods = mods.CheckWorkshopNotSync();
            if(unSyncMods.Count > 0)
            {
                UnsyncModTipBorder.Visibility = Visibility.Visible;
                var str = new StringBuilder("检测到以下mod未与创意工坊保持同步：\n");
                foreach(var mod in unSyncMods)
                {
                    str.AppendLine(mod);
                }
                str.Append("请先开启游戏安装/更新这些mod");
                UnsyncModTip.Text = str.ToString();
            }
            else
            {
                UnsyncModTipBorder.Visibility = Visibility.Collapsed;
            }

            foreach(var mod in mods.List)
            {
                ModListStackPanel.Children.Add(new ModItemUI(mod));
            }

            string lang;
            if(option.Dict.TryGetValue("Language", out lang))
            {
                foreach (var item in OptionLang.Items)
                {
                    if (((item as ComboBoxItem)?.DataContext as string)?.Equals(lang) ?? false)
                    {
                        OptionLang.SelectedItem = item;
                    }
                }
            }

            SavedModStatus.Children.Clear();
            foreach(var savedmod in myConfig.Mods)
            {
                SavedModStatus.Children.Add(new SavedModItemList(savedmod, (SavedModList list)=> {
                    myConfig.Mods.Remove(list);
                    UpdateConfigUI();
                }));
            }

            PathOptionAutoConfig.IsChecked = myConfig.ReadFromSteam;

        }

        private void OptionSave_Click(object sender, RoutedEventArgs e)
        {
            bool finded = false;
            foreach(var proc in System.Diagnostics.Process.GetProcesses())
            {
                if(proc.ProcessName == "isaac-ng")
                {
                    finded = true;
                }
            }
            if (finded)
            {
                if(MessageBox.Show("检测到游戏正在运行，此时保存配置可能不会生效，请先关闭游戏。按确定键继续执行，按取消键返回。", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                {
                    return;
                }
            }

            //resync
            option.Dict["EnableDebugConsole"] = (OptionConsoleEnabled.IsChecked ?? false) ? "1" : "0";
            option.Dict["EnableMods"] = (OptionModEnabled.IsChecked ?? false) ? "1" : "0";
            option.Dict["PauseOnFocusLost"] = (PauseOnFocusLostEnabled.IsChecked ?? false) ? "1" : "0";
            option.Dict["MouseControl"] = (MouseControlEnabled.IsChecked ?? false) ? "1" : "0";

            if (OptionLang.SelectedItem != null)
            {
                string str = ((OptionLang.SelectedItem as ComboBoxItem)?.DataContext as string) ?? "";
                if(str.Length > 0)
                {
                    option.Dict["Language"] = str;
                }
            }

            string error = option.SaveOption();
            if(error != null)
            {
                MessageBox.Show(error, "保存错误");
            }
            else
            {
                MessageBox.Show("配置保存成功","提示");
            }
        }
        private void OptionAbout_Click(object sender, RoutedEventArgs e)
        {
            new AboutWindow().ShowDialog();
        }
        private void ModListRefresh_Click(object sender, RoutedEventArgs e)
        {
            mods.UpdateList();
            UpdateConfigUI();
        }

        private void ModListSave_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(mods.SaveLists(),"提示");
        }

        private void AddNewSnapShot(object sender, RoutedEventArgs e)
        {
            myConfig.SnapshootNewList(mods);
            UpdateConfigUI();
        }
        
        private void ReloadSnapshot(object sender, RoutedEventArgs e)
        {
            if (!myConfig.LoadAll())
            {
                MessageBox.Show("配置文件读取失败");
            }
            else
            {
                UpdateConfigUI();
            }

        }
        private void SaveSnapshots(object sender, RoutedEventArgs e)
        {
            myConfig.SaveAll();
        }

        private void SetupGamePath(object sender, RoutedEventArgs e)
        {
            if (PathOptionAutoConfig.IsChecked ?? false)
            {
                myConfig.ReadFromSteam = true;
                if (config.RefindGamePath())
                    myConfig.SaveAll();
            }
            else
            {
                var dialog = new Microsoft.Win32.OpenFileDialog();
                dialog.Filter = "游戏主程序(isaac-ng.exe)|isaac-ng.exe";
                dialog.CheckFileExists = true;
                if(dialog.ShowDialog() ?? false)
                {
                    string path = dialog.FileName;
                    if (!path.EndsWith("isaac-ng.exe"))
                    {
                        MessageBox.Show("需要选择游戏主程序isaac-ng.exe以确认游戏路径","设置失败");
                        return;
                    }
                    myConfig.ReadFromSteam = false;
                    myConfig.GamePath = path.Substring(0,path.Length - "isaag-ng.exe".Length);
                    myConfig.SaveAll();
                    ReloadConfigs();
                    UpdateConfigUI();

                }
            }
        }
    }
}
